package com.pzhuweb.sgblog.annotation.aspect;

import com.alibaba.fastjson.JSON;
import com.pzhuweb.sgblog.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 鄧浩奇
 * @classname LogAspect
 * @description 切面类
 * @since 2023/7/21 16:45
 **/

@Component
@Aspect
@Slf4j
public class LogAspect {

    /*
     * @annotation() 里面写自定义注解的全类名
     * */

    @Pointcut("@annotation(com.pzhuweb.sgblog.annotation.SystemLog)")  // 切点方法
    public void pt() {}

    /*
     * 通知方法
     * */
    @Around("pt()")
    public Object pointLog(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed;
        try {
            handleBefore(pjp);  // 方法执行之前调用；由于方法需要获取被增强方法的信息，所以把pjp传入
            proceed = pjp.proceed();
            handleAfter(proceed);
        } finally {
            // 结束后换行
            log.info("========END=======" + System.lineSeparator());
        }

        return proceed;
    }

    private void handleAfter(Object res) {
        // 打印出参
        log.info("Response       : {}",JSON.toJSONString(res));
    }

    private void handleBefore(ProceedingJoinPoint pjp) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();  // request 里面封装了 http 报文

        // 获取被增强方法上的注解对象
        SystemLog systemLog = getSystemLog(pjp);


        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURI());
        // 打印描述信息
        log.info("BusinessName   : {}",systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}",request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",pjp.getSignature().getDeclaringTypeName(),pjp.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(pjp.getArgs()));
    }

    // 获取方法上面的SystemLog注解中的描述信息（获取自定义注解）
    private SystemLog getSystemLog(ProceedingJoinPoint pjp) {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        return methodSignature.getMethod().getAnnotation(SystemLog.class);
    }
}
